<?php
namespace app\api\controller\agent;

use think\Request;
use app\common\model\user\User as UserModel;
use think\Db;
use app\common\model\power\Rolepower;
use app\api\controller\Pub;
use app\api\controller\Base;
use app\common\model\customer\Customer as CustomerModel;
class Custmanage extends Base
{
     public function initialize()
    {
        parent::initialize();
        $this->is_login();
        Rolepower::powerguard('303002'); //客户管理
    }

    private function is_login()
    {
        $data = UserModel::is_sessionlogin();
        if (!$data['code']) {
            $data['options'] = 'relogin';
            json($data)->send();
            exit;
        }
    }

    // 客户列表
    public function customerList(Request $request)
    {
        $page=$request->get('page');
        $pageSize=$request->get('pageSize');
        $keyword=$request->get('keyword');
        $pub=new Pub();
        $user_id=$pub->userid();

        $role= Db::name('user')->where('UserId',$user_id)->value('Role');
        if ($role == 304) { // 代理商员工
            $agency_ids = [$user_id];
        } elseif ($role == 303) { // 代理商管理员
            $agency_id = Db::name('user_agency')->where('user_id', $user_id)->value('agency_id');
            $agency_ids = Db::name('user_agency')->where('agency_id', $agency_id)->column('user_id');
        } 

        $list = Db::name('customer')->alias('c')->whereIn('c.AgentId', $agency_ids);
        if($keyword){
            $list=$list->where('c.UserName','like',"%$keyword%");
        }
        $list = $list->order('AddTime desc')
                ->join('user u','c.AgentId=u.UserId')
                ->field('c.*,u.Name as agent_name,u.Iphone as agent_phone')
                ->paginate([
            'list_rows' => $pageSize,
            'page'      => $page
        ]);
        return json(['code'=>1, 'msg'=>'success', 'data'=>$list]);
    }

    // 添加客户
    public function customerAdd(Request $request)
    {
        $pub=new Pub();
        $user_id=$pub->userid();

        $data = $request->post();
        if (empty($data['UserName']) || empty($data['Name']) || empty($data['Address']) || empty($data['Tel'])) {
            return json(['code'=>0, 'msg'=>'参数不完整']);
        }
        $customer = new CustomerModel();
        $customer->Name = $data['Name'];
        $customer->Tel = $data['Tel'];
        $customer->Address = $data['Address'];
        $customer->UserName= $data['UserName'];
        $customer->OtherTel = $data['OtherTel'] ?? null;
        $customer->AddTime = date('Y-m-d H:i:s');
        $customer->AgentId = $user_id;
        $customer->save();
        // 关联到当前用户
        Db::name('user_customer')->insert([
            'user_id' => $user_id,
            'customer_id' => $customer->CustomerId,
        ]);
        return json(['code'=>1, 'msg'=>'添加成功']);
    }

    //客户信息修改
    public function customerEdit(Request $request)
    {
         $data = $request->post();
        if (empty($data['UserName']) || empty($data['Name']) || empty($data['Address']) || empty($data['Tel'])) {
            return json(['code'=>0, 'msg'=>'参数不完整']);
        }
        $customer = CustomerModel::get($data['CustomerId']);
        if (!$customer) {
            return json(['code'=>0, 'msg'=>'用户不存在']);
        }
        $customer->Name = $data['Name'];
        $customer->UserName = $data['UserName'];
        $customer->Address = $data['Address'];
        $customer->Tel = $data['Tel'];
        $customer->save();
        return json(['code'=>1, 'msg'=>'修改成功']);
    }

    //客户删除
    public function customerDel(Request $request)
    {
        $CustomerId = $request->post('CustomerId');
        if (empty($CustomerId)) {
            return json(['code'=>0, 'msg'=>'参数不完整']);
        }
        CustomerModel::destroy($CustomerId);
        Db::name('user_customer')->where('customer_id', $CustomerId)->delete();
        return json(['code'=>1, 'msg'=>'删除成功']);
    }

    //将客户分给指定代理商员工
    public function customerChangeAgency(Request $request)
    {   
         Rolepower::powerguard('303001');
        $user_id = $request->post('user_id');
        $customer_id = $request->post('customer_id');
        if (empty($user_id) || empty($customer_id)) {
            return json(['code'=>0, 'msg'=>'参数不完整']);
        }
        // 重新分配
        Db::name('customer')->where('CustomerId', $customer_id)->update(['AgentId' => $user_id]);
        return json(['code'=>1, 'msg'=>'分配成功']);
    }
} 